'''
Evaluation Tasks

The evaluation tasks generate scores for phenotypes.
'''
import os
import time
import random

from dexen import BaseSlaveTask

from slave_tasks import common
from individual import Individual

common.enable_hou_module()
import hou

#Function to run Houdini
def run_houdini_eval(ind, file_name):
    #write the phenotype to a temporary file
    phen_folder_path = os.path.join(common.HOU_FOLDER_PATH, "temp")
    common.create_folder(phen_folder_path)
    phen_file_path = os.path.join(phen_folder_path, "temp.bgeo")
    f = open(phen_file_path, "wb")
    f.write(ind.phenotype)
    f.close()
    #open the hipnc file
    hou_file_path = os.path.join(common.HOU_FOLDER_PATH, file_name)
    hou.hipFile.load(hou_file_path)
    #load the geometry into the phenotype node
    phenotype_node = hou.node(common.PHENOTYPE_NODE_PATH)
    phenotype_node.setParms(dict([["file",phen_file_path]]))
    #get the result from the score node
    score_node = hou.node(common.SCORE_NODE_PATH)
    score_node.cook()
    score = score_node.geometry().attribValue(common.SCORE_ATTRIB_NAME)
    #return the score
    return score

#Slave task for evaluation A
class EvalAreaTask(BaseSlaveTask):
    def __init__(self):
        pass
    def __execute__(self, master_state, inds):
        #process individuals
        for ind in inds:
            assert isinstance(ind, Individual)
            ind.score_area = run_houdini_eval(ind, common.HOU_EVALA_FILE_NAME)
            ind.archive_data("score_area.txt", str(ind.score_area))
            #delete phenotype if it is no longer required
            if ind.score_area and ind.score_vol:
                ind.phenotype = "stripped"
        #return the inds with the scores added 
        return inds

#Slave task for evaluation B
class EvalVolTask(BaseSlaveTask):
    def __init__(self):
        pass
    def __execute__(self, master_state, inds):
        #process individuals
        for ind in inds:
            assert isinstance(ind, Individual)
            ind.score_vol = run_houdini_eval(ind, common.HOU_EVALB_FILE_NAME)
            ind.archive_data("score_vol.txt", str(ind.score_vol))
            #delete phenotype if it is no longer required
            if ind.score_area and ind.score_vol:
                ind.phenotype = "stripped"
        #return the inds with the scores added 
        return inds

